﻿using System;
using System.IO;
using System.Configuration;


namespace Xiaozhou.Utility
{
    public class Logger
    {
        private static readonly string TYPE_INFO = "Info";
        private static readonly string TYPE_WARN = "Warn";
        private static readonly string TYPE_ERROR = "Error";

        private static readonly string logPath;

        private static readonly object _lockedObject = new object();

        static Logger()
        {
            logPath = ConfigurationManager.AppSettings["LogPath"];
        }

        private static void Log(string msg)
        {
            lock (_lockedObject)
            {
                StreamWriter writer = null;


                try
                {
                    string logFile = Path.Combine(logPath, string.Format("Log_{0:yyyy-MM-dd}.log", DateTime.Today));
                    FileInfo file = new FileInfo(logFile);
                    writer = file.AppendText();
                    writer.WriteLine(msg);
                }
                //catch
                //{
                //}
                finally
                {
                    if (writer != null)
                    {
                        writer.Flush();
                        writer.Dispose();
                    }
                }
            }
        }

        private static void WriteLine(string type, string msg)
        {
            Log(string.Format("{0:yyyy-MM-dd HH:mm:ss}\t {1}\t {2}", DateTime.Now, type, msg));
        }

        public static void Info(string msg)
        {
            WriteLine(TYPE_INFO, msg);
        }

        public static void Info(string title, string content)
        {
            WriteLine(TYPE_INFO, title + "\n" + content);
        }

        public static void Error(string msg)
        {
            WriteLine(TYPE_ERROR, msg);
        }

        public static void Error(string title, string content)
        {
            WriteLine(TYPE_ERROR, title + "\n" + content);
        }

        public static void Warn(string msg)
        {
            WriteLine(TYPE_WARN, msg);
        }

        public static void Warn(string title, string content)
        {
            WriteLine(TYPE_WARN, title + "\n" + content);
        }

    }
}